<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

use vod\Request\V20170321\CreateUploadVideoRequest;
use vod\Request\V20170321\RefreshUploadVideoRequest;
use vod\Request\V20170321 as vod;
use OSS\OssClient;
use OSS\Core\OssException;

function http_post($url, $json){
    $request = new HttpRequest();
    $request->setUrl($url);
    $request->setMethod(HTTP_METH_POST);

    $request->setHeaders(array(
        'Postman-Token' => '97645f64-aafa-4354-9f11-574d31b79766',
        'Cache-Control' => 'no-cache',
        'Content-Type' => 'application/json'
    ));

    $request->setBody($json);

    try {
        $response = $request->send();

        echo $response->getBody();
    } catch (HttpException $ex) {
        echo $ex;
    }
}

function cur_post($url ,$json){
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $json,
        CURLOPT_HTTPHEADER => array(
            "Cache-Control: no-cache",
            "Content-Type: application/json",
            "Postman-Token: 049c6b03-73c7-4964-bdbf-190c1e1ec765"
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
//        echo $response;
    }
    return $response;
}

function getBank(){
    $arr = array(
        "建设银行"=>'CCB',
        "浦发银行"=>'SPDB',
        "华夏银行"=>'HXB',
        "光大银行"=>'CEB',
        "广发银行"=>'GDB',
        "农业银行"=>'ABC',
        "中信银行"=>'CITIC',
        "北京银行"=>'BOB',
        "民生银行"=>'CMBC',
        "宁波银行"=>'NBCB',
        "交通银行"=>'BCOM',
        "北京农商"=>'BJRCB',
        "广州农商"=>'GRCB',
        "九江银行"=>'JJCCB',
        "兴业银行"=>'CIB',
        "中国银行"=>'BOC',
        "上海银行"=>'BOS',
        "江苏银行"=>'JSBK',
    );
    return array_flip($arr);
}
//4.1.银行编码
function bankCode($key){
    $arr = array(
        "建设银行"=>'CCB',
        "浦发银行"=>'SPDB',
        "华夏银行"=>'HXB',
        "光大银行"=>'CEB',
        "广发银行"=>'GDB',
        "农业银行"=>'ABC',
        "中信银行"=>'CITIC',
        "北京银行"=>'BOB',
        "民生银行"=>'CMBC',
        "宁波银行"=>'NBCB',
        "交通银行"=>'BCOM',
        "北京农商"=>'BJRCB',
        "广州农商"=>'GRCB',
        "九江银行"=>'JJCCB',
        "兴业银行"=>'CIB',
        "中国银行"=>'BOC',
        "上海银行"=>'BOS',
        "江苏银行"=>'JSBK',
    );
    return $arr[$key];
}
//设备类型
function equipType($key){
    $arr = array(
        "pc"=>10,
        "ios"=>21,
        "android"=>22,
        "其他"=>90
    );
    return $arr[$key];
}


include_once dirname(dirname(dirname(dirname((__FILE__)))))."/".'api/video/aliyun-php-sdk-core/Config.php';
include_once dirname(dirname(dirname(dirname((__FILE__)))))."/".'api/video/aliyun-php-sdk-core/Profile/DefaultProfile.php';
//include_once dirname(dirname(dirname(dirname((__FILE__)))))."/".'api/video/aliyun-php-sdk-core/DefaultAcsClient.php';
//获取播放凭证
function get_play_auth($client, $videoId) {
    $request = new vod\GetVideoPlayAuthRequest();
    $request->setVideoId($videoId);
    $request->setAuthInfoTimeout(3600);  // 播放凭证过期时间，默认为100秒，取值范围100~3600；注意：播放凭证用来传给播放器自动换取播放地址，凭证过期时间不是播放地址的过期时间
    $request->setAcceptFormat('JSON');
    $response = $client->getAcsResponse($request);
    return $response;
}


//获取播放地址
function get_play_info($client, $videoId) {
    $request = new vod\GetPlayInfoRequest();
    $request->setVideoId($videoId);
    $request->setAuthTimeout(3600*24);    // 播放地址过期时间（只有开启了URL鉴权才生效），默认为3600秒，支持设置最小值为3600秒
    $request->setAcceptFormat('JSON');
    return $client->getAcsResponse($request);
}

// 使用账号AK初始化VOD客户端
function init_vod_client($accessKeyId, $accessKeySecret) {
    $regionId = 'cn-shanghai';  // 点播服务所在的Region，国内请填cn-shanghai，不要填写别的区域
    $profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
    return new DefaultAcsClient($profile);
}

// 获取视频上传地址和凭证
function create_upload_video($vodClient) {
    $request = new vod\CreateUploadVideoRequest();

    $request->setTitle("视频标题");        // 视频标题(必填参数)
    $request->setFileName("文件名称.mov"); // 视频源文件名称，必须包含扩展名(必填参数)

    $request->setDescription("视频描述");  // 视频源文件描述(可选)
    $request->setCoverURL("http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png"); // 自定义视频封面(可选)
    $request->setTags("标签1,标签2"); // 视频标签，多个用逗号分隔(可选)

    return $vodClient->getAcsResponse($request);
}

// 刷新上传凭证
function refresh_upload_video($vodClient, $videoId) {
    $request = new vod\RefreshUploadVideoRequest();
    $request->setVideoId($videoId);
    return $vodClient->getAcsResponse($request);
}

// 使用上传凭证和地址信息初始化OSS客户端（注意需要先Base64解码并Json Decode再传入）
function init_oss_client($uploadAuth, $uploadAddress) {
    $ossClient = new OssClient($uploadAuth['AccessKeyId'], $uploadAuth['AccessKeySecret'], $uploadAddress['Endpoint'],
        false, $uploadAuth['SecurityToken']);
    $ossClient->setTimeout(86400*7);    // 设置请求超时时间，单位秒，默认是5184000秒, 建议不要设置太小，如果上传文件很大，消耗的时间会比较长
    $ossClient->setConnectTimeout(10);  // 设置连接超时时间，单位秒，默认是10秒
    return $ossClient;
}

// 使用简单方式上传本地文件：适用于小文件上传；最大支持5GB的单个文件
// 更多上传方式参考：https://help.aliyun.com/document_detail/32103.html
function upload_local_file($ossClient, $uploadAddress, $localFile) {
    return $ossClient->uploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
}

// 大文件分片上传，支持断点续传；最大支持48.8TB
function multipart_upload_file($ossClient, $uploadAddress, $localFile) {
    return $ossClient->multiuploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
}


function dr_mylang() {

}
//是否是移动手机号
function is_mobile($str, $is_more = FALSE)
{
    if ($is_more) {
        $_str = explode(",", $str);
        $count = count($_str);
        for ($i = 0; $i < $count; $i++) {
            if (!is_mobile($_str[$i])) return false;
        }
        return true;
    } else {
        return (preg_match('/^1[34578]\d{9}$/', $str) ? true : false);
    }
}
function choice_template($type =1)
{
    if($type == 1){
        return "SMS_133276348";
    }else{
        return "SMS_133970101";
    }
}
/**
 *  数据导入
 * @param string $file excel文件
 * @param string $sheet
 * @return string   返回解析数据
 * @throws PHPExcel_Exception
 * @throws PHPExcel_Reader_Exception
 */
function importExecl($file='', $sheet=0){
    header("Content-type: text/html; charset=utf-8");
    $file = iconv("utf-8", "gb2312", $file);   //转码
    if(empty($file) OR !file_exists($file)) {
        die('file not exists!');
    }
//    include('app/Classes/PHPExcel.php');  //引入PHP EXCEL类
    require_once FCPATH. 'app/Classes/PHPExcel.php';
    require_once FCPATH. 'app/Classes/PHPExcel/IOFactory.php';
    require_once FCPATH. 'app/Classes/PHPExcel/Reader/Excel5.php';
    require_once FCPATH.'app/Classes/PHPExcel/Reader/Excel2007.php';
    $objRead = new PHPExcel_Reader_Excel2007();   //建立reader对象
    if(!$objRead->canRead($file)){
        $objRead = new PHPExcel_Reader_Excel5();
        if(!$objRead->canRead($file)){
            die('No Excel!');
        }
    }
    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

    $obj = $objRead->load($file);  //建立excel对象
    $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表
    $columnH = $currSheet->getHighestColumn();   //取得最大的列号
//    echo $columnH;exit;
    $columnCnt = array_search($columnH, $cellName);
    $rowCnt = $currSheet->getHighestRow();   //获取总行数
//    var_dump($columnCnt);exit;
    $data = array();
    $stu = array();
    $cols = '';
    for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
        for($_column=0; $_column<=$columnCnt; $_column++){
            $cellId = $cellName[$_column].$_row;
            $cellValue = $currSheet->getCell($cellId)->getValue();
//            $cellValue = $currSheet->getCell($cellId)->getCalculatedValue();  #获取公式计算的值
            if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
                $cellValue = $cellValue->__toString();
            }
            //进行组装数据

//            if($currSheet->getCell($cellName[$_column].'1')->getValue() == "学校"){
//                $colum = "school";
//            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="姓名"){
//                $colum = "name";
//            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="联系电话"){
//                $colum = "phone";
//            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="年级"){
//                $colum = "grade";
//            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="出生日期"){
//                $colum = "birthday";
//            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="身份证号"){
//                $colum = "id_num";
//            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="省"){
//                $colum = "province";
//            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="区"){
//                $colum = "area";
//            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() == "性别"){
//                $colum = "sex";
//            }else{
//                $colum = "";
//            }
//            if($_row > 1 && !empty($colum)){
//                $stu[$_row-2][$colum] = $cellValue;
////                $stu[$_row-2]['source'] = $filename;
//            }
//            $data[$_row][$cols] = $cellValue;
            $data[$_row][$cellName[$_column]] = $cellValue;
        }
    }

    return $data;
}
function importExeclss($file='',$filename = '', $file_type = 'xls', $sheet=0){
    header("Content-type: text/html; charset=utf-8");
//    $file = iconv("utf-8", "gb2312", $file);   //转码
//    if(empty($file) OR !file_exists($file)) {
//        die('file not exists!');
//    }
//    include('app/Classes/PHPExcel.php');  //引入PHP EXCEL类
    require_once FCPATH. 'app/Classes/PHPExcel.php';
    require_once FCPATH. 'app/Classes/PHPExcel/IOFactory.php';
    require_once FCPATH. 'app/Classes/PHPExcel/Reader/Excel5.php';
    require_once FCPATH.'app/Classes/PHPExcel/Reader/Excel2007.php';

//    $objRead = new PHPExcel_Reader_Excel2007();   //建立reader对象
//    if(!$objRead->canRead($file)){
//        $objRead = new PHPExcel_Reader_Excel5();
//        if(!$objRead->canRead($file)){
//            die('No Excel!');
//        }
//    }
    //判断上传文件类型
    $obj = array();
    $excel_type = array('xls','csv','xlsx');
    if(!in_array($file_type,$excel_type)){
        echo "不是excel 文件";exit;
    }
    if($file_type == 'xls'){
        $objReader = PHPExcel_IOFactory::createReader('Excel5');
    }else if($file_type == 'xlsx'){
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    }else if($file_type == 'csv'){
        $objReader = PHPExcel_IOFactory::createReader('CSV');
    }

    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');


//    $obj = $objRead->load($file);  //建立excel对象
//    $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表
//    $columnH = $currSheet->getHighestColumn();   //取得最大的列号
//    $columnCnt = array_search($columnH, $cellName);
//    $rowCnt = $currSheet->getHighestRow();   //获取总行数
    // 修改之后的读取数据
    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($file);
    $currSheet = $objPHPExcel->getSheet();
    $rowCnt = $currSheet->getHighestRow();
    $columnH = $currSheet->getHighestColumn();
    $columnCnt = array_search($columnH, $cellName);

//    print_r($objWorksheet);exit;
    $data = array();
    $stu = array();

    for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
        for($_column=0; $_column<=$columnCnt; $_column++){
            $cellValue = '';
            $cellId = $cellName[$_column].$_row;
            $cellValue = $currSheet->getCell($cellId)->getValue();
//            $cellValue = $currSheet->getCell($cellId)->getCalculatedValue();  #获取公式计算的值
            if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
                $cellValue = $cellValue->__toString();
            }

            if($currSheet->getCell($cellName[$_column].'1')->getValue() == "学校"){
                $colum = "school";
            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="姓名"){
                $colum = "name";
            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="联系电话" || $currSheet->getCell($cellName[$_column].'1')->getValue() =="联系方式"){
                $colum = "phone";
            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="年级" || $currSheet->getCell($cellName[$_column].'1')->getValue() == "班级"){
                $colum = "grade";
            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="出生日期"){
                $colum = "birthday";
            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="身份证号"){
                $colum = "id_num";
            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="省"){
                $colum = "province";
            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() =="区"){
                $colum = "area";
            }else if($currSheet->getCell($cellName[$_column].'1')->getValue() == "性别"){
                $colum = "sex";
            }else{
                $colum = "";
            }
            if($_row > 1 && !empty($colum)){
                if($colum == "id_num" && strpos($cellValue,'+17')){
                    $stu[$_row-2][$colum] = '';
                }else if($colum == 'birthday' && !empty($cellValue)){
                    $stu[$_row-2][$colum] = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($cellValue ));
                }else{
                    $stu[$_row-2][$colum] = $cellValue;
                }
                $stu[$_row-2]['source'] = $filename;
            }
//            $data[$_row][$cellName[$_column]] = $cellValue;
        }

    }
//    print_r($stu);exit;
//    return $data;
    return $stu;
}

/**
 * 导入excel
 *
*/
function importExcels($inputFileName){
    error_reporting(E_ALL); //开启错误
    set_time_limit(0); //脚本不超时

    date_default_timezone_set('Europe/London'); //设置时间

    /** Include path **/
    set_include_path(get_include_path() . PATH_SEPARATOR . 'http://www.cnblogs.com/../Classes/');//设置环境变量

    /** PHPExcel_IOFactory */
//    include 'PHPExcel/IOFactory.php';
    include 'app/Classes/PHPExcel/IOFactory.php';

    $inputFileType = 'Excel5';    //这个是读 xls的
//    $inputFileType = 'Excel2007';//这个是计xlsx的
//$inputFileName = './sampleData/example2.xls';
//    $inputFileName = './sampleData/book.xlsx';

    echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
    /*
    $sheet = $objPHPExcel->getSheet(0);
    $highestRow = $sheet->getHighestRow(); //取得总行数
    $highestColumn = $sheet->getHighestColumn(); //取得总列
    */
    $objWorksheet = $objPHPExcel->getActiveSheet();//取得总行数
    $highestRow = $objWorksheet->getHighestRow();//取得总列数

    echo 'highestRow='.$highestRow;
    echo "<br>";
    $highestColumn = $objWorksheet->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
    echo 'highestColumnIndex='.$highestColumnIndex;
    echo "<br />";
    $headtitle=array();
    for ($row = 1;$row <= $highestRow;$row++)
    {
        $strs=array();
        //注意highestColumnIndex的列数索引从0开始
        for ($col = 0;$col < $highestColumnIndex;$col++)
        {
            $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
        }
        $info = array(
            'word1'=>"$strs[0]",
            'word2'=>"$strs[1]",
            'word3'=>"$strs[2]",
            'word4'=>"$strs[3]",
        );
        //在这儿，你可以连接，你的数据库，写入数据库了
        print_r($info);
        echo '<br />';
    }

}
/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */
function send_posts($url, $post_data) {

    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间（单位:s）
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}
/**
 * Curl版本
 * 使用方法：
 * $post_string = "app=request&version=beta";
 * request_by_curl('http://www.jb51.net/restServer.php', $post_string);
 */
function request_by_curl($remote_server, $post_string) {
    header('');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $remote_server);
    curl_setopt($ch, CURLOPT_POSTFIELDS, '' . $post_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "jb51.net's CURL Example beta");
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
/*
获取token
@api_url	接口地址
@args	接口所需参数
*/
function ec_getToken($api_url,$args ){ // 模拟提交数据函数
    set_time_limit(0);
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $api_url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $args); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); //相当关键，这句话是让curl_exec($ch)返回的结果可以进行赋值给其他的变量进行，json的数据操作，如果没有这句话，则curl返回的数据不可以进行人为的去操作（如json_decode等格式操作）
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno'.curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据
}
/*
获取员工及部门信息
@api_url    api地址
@args	api所需参数
@token_companyId    token值跟公司id
*/
function ec_getData($api_url,$args,$token_companyId){
    set_time_limit(0);
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $api_url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $args); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容

    curl_setopt($curl, CURLOPT_HTTPHEADER,$token_companyId );//这里设置token验证权限

    curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); //相当关键，这句话是让curl_exec($ch)返回的结果可以进行赋值给其他的变量进行，json的数据操作，如果没有这句话，则curl返回的数据不可以进行人为的去操作（如json_decode等格式操作）
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno'.curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据
}